package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SkuItemVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        try {
            BigDecimal min = new BigDecimal((String) params.get("min"));
            wrapper.ge("price", min);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            BigDecimal max = new BigDecimal((String) params.get("max"));
            if (max.compareTo(new BigDecimal("0")) == 1) {
                wrapper.le("price", max);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SkuItemVO item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVO skuItemVO = new SkuItemVO();

        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 获取sku的信息
            SkuInfoEntity skuInfo = this.getById(skuId);
            skuItemVO.setSkuInfo(skuInfo);

            return skuInfo;
        }, executor);

        CompletableFuture<Void> spuInfoDescFuture = skuInfoFuture.thenAcceptAsync(skuInfo -> {
            // 获取SPU的商品介绍信息
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(skuInfo.getSpuId());
            skuItemVO.setSpuInfoDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> skuBaseAttrsFuture = skuInfoFuture.thenAcceptAsync(skuInfo -> {
            // 获取sku的属性分组信息
            List<AttrGroupEntity> attrGroupEntityList = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", skuInfo.getCatalogId()));
            List<SkuItemVO.SpuItemAttrGroupVO> spuItemAttrGroupVOList = attrGroupEntityList.stream().map(attrGroupEntity -> {
                SkuItemVO.SpuItemAttrGroupVO spuItemAttrGroupVO = new SkuItemVO.SpuItemAttrGroupVO();
                spuItemAttrGroupVO.setGroupName(attrGroupEntity.getAttrGroupName());

                Long attrGroupId = attrGroupEntity.getAttrGroupId();
                List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

                List<SkuItemVO.SpuItemAttrVO> spuItemAttrVOList = attrAttrgroupRelationEntityList.stream().map(attrAttrgroupRelationEntity -> {
                    Long attrId = attrAttrgroupRelationEntity.getAttrId();
                    ProductAttrValueEntity productAttrValueEntity = productAttrValueService.getOne(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", skuInfo.getSpuId()).eq("attr_id", attrId));

                    SkuItemVO.SpuItemAttrVO spuItemAttrVO = new SkuItemVO.SpuItemAttrVO();
                    spuItemAttrVO.setAttrName(productAttrValueEntity.getAttrName());
                    spuItemAttrVO.setAttrValue(productAttrValueEntity.getAttrValue());

                    return spuItemAttrVO;
                }).collect(Collectors.toList());

                spuItemAttrGroupVO.setAttrVos(spuItemAttrVOList);

                return spuItemAttrGroupVO;
            }).collect(Collectors.toList());

            skuItemVO.setAttrGroups(spuItemAttrGroupVOList);
        }, executor);

        CompletableFuture<Void> skuSaleAttrsFuture = skuInfoFuture.thenAcceptAsync(skuInfo -> {
            // 获取销售属性
            List<SkuItemVO.SkuItemSaleAttrVO> skuItemSaleAttrVO = skuSaleAttrValueService.getSaleAttrsBySpuId(skuInfo.getSpuId());
            skuItemVO.setSaleAttrs(skuItemSaleAttrVO);
        }, executor);

        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            // 获取sku的图片信息
            QueryWrapper<SkuImagesEntity> wrapper = new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId);
            List<SkuImagesEntity> images = skuImagesService.list(wrapper);
            skuItemVO.setSkuImages(images);
        }, executor);

        CompletableFuture.allOf(spuInfoDescFuture, skuBaseAttrsFuture, skuSaleAttrsFuture, skuImagesFuture).get();

        return skuItemVO;
    }

}